package com.gongpingjialoan.network;

import android.os.AsyncTask;

import com.gongpingjialoan.data.KCookie;
import com.gongpingjialoan.utility.CRequest;
import com.gongpingjialoan.utility.Utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/17.
 */
/** @deprecated */
public class NetWork {

    private final static int REQUEST_TIMEOUT = 10000;

    private final static int SO_TIMEOUT = 10000;

    private Map<String, Object> paramsMap = new HashMap<String, Object>();

    private String url;

    private int type;

    public NetDataJson.OnNetDataJsonListener mListener;

    private GetJsonTask mTask;

    private class GetJsonTask extends AsyncTask<String, String, JSONObject> {
        @Override
        protected JSONObject doInBackground(String... args) {
            DefaultHttpClient client = new DefaultHttpClient();
            StringBuilder builder = new StringBuilder();
            JSONObject jsonObject;

            try {

                HttpResponse response;
                HttpParams httpParams = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
                if (args.length > 1 && args[1].equals("post")) {
                    String url = CRequest.UrlPage(args[0]);
                    Map<String, String> mapRequest = CRequest.URLRequest(args[0]);
                    HttpPost post = new HttpPost(url);

                    String session = NetUtils.getInstance().getLocalCookie();
                    if (null != session) {
                        post.addHeader("cookie", session);
                    }

                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    for (String strRequestKey : mapRequest.keySet()) {
                        String strRequestValue = mapRequest.get(strRequestKey);
                        params.add(new BasicNameValuePair(strRequestKey, strRequestValue));
                    }
                    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    response = client.execute(post);
                } else {
                    HttpGet get = new HttpGet(args[0]);
                    String session = NetUtils.getInstance().getLocalCookie();
                    if (null != session) {
                        get.addHeader("cookie", session);
                    }
                    response = client.execute(get);
                }
                HttpEntity entity = response.getEntity();

                List<Cookie> cookies = client.getCookieStore().getCookies();
                if (cookies.isEmpty()) {
                } else {
                    for (int i = 0; i < cookies.size(); i++) {
                        if (null != cookies.get(i).getName() && null != cookies.get(i).getValue()) {
                            if (cookies.get(i).getName().equals("sessionid")) {
                                KCookie cookie = new KCookie(cookies.get(i).getName(), cookies.get(i).getValue());
                                NetUtils.getInstance().setLocalCookie(cookie);
                            }
                        }
                    }
                }

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                    builder.append(s);
                }
                Utils.LogD("..........http builder = " + builder.toString());
                if (builder.toString().indexOf("Sorry, Server Error!") >= 0) {
                    mListener.onDataJsonError("网络连接超时，请检查您的网络连接。");
                    return null;
                }

                jsonObject = new JSONObject(builder.toString());

            } catch (ConnectTimeoutException e) {
                mListener.onDataJsonError("网络连接超时，请检查您的网络连接。");
                e.printStackTrace();
                return null;
            } catch (SocketTimeoutException e) {
                mListener.onDataJsonError("获取数据超时，请检查您的网络连接。");
                e.printStackTrace();
                return null;
            } catch (Exception e) {

                return null;
            }
            return jsonObject;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            String status = "failed";
            if (null == json) {
                mListener.onDataJsonError("数据异常，请检查网络连接或稍后重试。");
                return;
            }
            try {
                status = json.getString("status");
                if (!status.equals("success")) {
                    mListener.onDataJsonError(json.getString("msg"));
                } else {
                    mListener.onDataJsonUpdate(json);
                }

            } catch (JSONException e) {
                mListener.onDataJsonError("没有数据，请检查网络连接。");
                e.printStackTrace();
            }

        }
    }


    public NetWork(NetDataJson.OnNetDataJsonListener listener) {
        mListener = listener;
    }


    public void cancelTask() {
        if (null != mTask) {
            mTask.cancel(true);
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void addParam(String key, Object value) {
        this.paramsMap.put(key.trim(), value);
    }

    public void request(String method) {
        String parms = encodeUrl(paramsMap);
        requestData(url + "?" + parms, method);
    }

    public static String encodeUrl(Map<String, Object> params) {
        if (params == null || params.size() == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            if (params.get(key) != null) {
                sb.append(key.trim()).append("=").append((params.get(key).toString())).append("&");
            }
        }
        return sb.toString();
    }

    public void requestData(String... args) {
        try {
            cancelTask();
            mTask = new GetJsonTask();

            Utils.LogD("requestData=" + NetDataJson.SERVER_DOMAIN + args[0] + "");

            if (args.length > 1) {
                mTask.execute(NetDataJson.SERVER_DOMAIN + args[0], args[1]);
            } else {
                mTask.execute(NetDataJson.SERVER_DOMAIN + args[0]);
            }

        } catch (Exception e) {
            Utils.LogD("获取数据异常：" + e.getMessage());
        }

    }
}
